package com.matrix.draft.sockettest.day10;

import com.matrix.draft.sockettest.day10.handler.ClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TcpPackageClient {

    private String host;
    private Integer port;

    public TcpPackageClient(String host, Integer port) {
        this.host = host;
        this.port = port;
    }

    public void run() {
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {
            new Bootstrap().group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // In
                            pipeline.addLast(new ClientHandler());
                        }
                    })
                    .connect(host, port)
                    .addListener(future -> {
                        if (future.isSuccess()) {
                            System.err.println("连接服务器成功...");
                        }
                    })
                    .sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {

        }
    }

    public static void main(String[] args) {
        new TcpPackageClient("127.0.0.1", 8080).run();
    }
}
